package uit.nfcmenu.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import uit.nfcmenu.webservice.CommonWS;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;


public class ImageHelper {
	static String tag = ImageHelper.class.getSimpleName();

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
		return createRoundedCornerBitmap(bitmap, 50, 50, roundPx);
	}

	private static Bitmap createRoundedCornerBitmap(Bitmap bitmap, 
			int w, int h, float roundPx) {
		// Log.i(tag, "getRoundedCornerBitmap(): w="+w+",h="+h);
		if (bitmap == null || w == 0 || h == 0) {
			return bitmap;
		}

		Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rectSrc = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final Rect rectDst = new Rect(0, 0, w, h);
		final RectF rectF = new RectF(rectDst);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rectSrc, rectDst, paint);

		return output;
	}

	private static Bitmap createSplitedCenterVerticalBitmap(Bitmap bitmap,
			int w, int h, int i) {
		// Log.i(tag, "createSplitedCenterVerticalBitmap(): w="+w+",h="+h);
		if (bitmap == null || w == 0 || h == 0) {
			return bitmap;
		}
		
		Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int centerSrc = bitmap.getHeight() / 2;
		final int centerDst = h / 2;
		final Rect rectSrc = new Rect(0, centerSrc - centerDst, bitmap.getWidth(), centerSrc + centerDst);
		final Rect rectDst = new Rect(0, 0, w, h);
		final RectF rectF = new RectF(rectDst);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRect(rectF,paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rectSrc, rectDst, paint);

		return output;
	}

	public static boolean setImageView(View imageView, String path) {
		Drawable drawable = Drawable.createFromPath(path);
		if (drawable != null) {
			imageView.setBackgroundDrawable(drawable);
			imageView.invalidate();
			return true;
		}
		return false;
	}

	public static boolean getImageViewWithRoundCorners(ImageView iv,
			String path, int pixels) {
		Drawable drawable = Drawable.createFromPath(path);
		if (drawable != null) {
			Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
			bitmap = createRoundedCornerBitmap(bitmap, iv.getWidth(), iv.getHeight(), pixels);
			if (bitmap != null) {
				iv.setImageBitmap(bitmap);
				return true;
			}
		} 
		
//		Log.e(tag, "getImageViewWithRoundCorners(): bitmap == null");
		return false;
	}
	
	public static boolean getImageViewWithRoundCorners(ImageView iv, Bitmap bitmap, int pixels) {
		//Log.w(tag, "getImageViewWithRoundCorners(): iv w="+iv.getWidth()+", h="+iv.getHeight());
		Bitmap output = createRoundedCornerBitmap(bitmap, iv.getWidth(), iv.getHeight(), pixels);
		if (output != null) {
			iv.setImageBitmap(output);
			return true;
		}
		
//		Log.e(tag, "getImageViewWithRoundCorners(): bitmap == null");
		return false;
	}


	public static boolean setViewWithRoundCorners(View iv,
			Bitmap bitmap, int w, int h, int cornerRadius) {
		//Log.w(tag, "getImageViewWithRoundCorners(): iv w="+w+", h="+h);
		Bitmap output = createRoundedCornerBitmap(bitmap, w, h, cornerRadius);
		return setImageView(iv, output);
	}

	private static boolean setImageView(View iv, Bitmap bitmap) {
		if (bitmap != null) {
			BitmapDrawable drawable = new BitmapDrawable(bitmap);
			if(iv instanceof ImageView) {
				((ImageView)iv).setImageDrawable(drawable);
			}
			else {
				iv.setBackgroundDrawable(drawable);
			}
			return true;
		}
//		Log.e(tag, "getImageViewWithRoundCorners(): bitmap == null");
		return false;
	}
	
	public static void setBackground(ImageView iv, Bitmap bitmap,
			int w, int h) {
		Bitmap output = createRoundedCornerBitmap(bitmap, w, h, 0);
		setImageView(iv, output);
	}
	
	public static void setImageSplitedCenterVertical(ImageView btnImage,
			Bitmap bitmap, int w, int h) {
		Bitmap output = createSplitedCenterVerticalBitmap(bitmap, w, h, 0);
		setImageView(btnImage, output);
	}

	public static void downloadFromUrl(String fileURL, String filePath) {
		// Log.w(tag, "downloadFromUrl(url=" + fileURL + "\nuri=" + filePath);
		// long startTime = System.currentTimeMillis();
		byte[] fileInBytes = downloadFileFromUrl(fileURL);

		// Convert the Bytes read to a String. 
		File file = new File(filePath);
		FileOutputStream fos;
		try {
			// Log.i(tag, "begin download file name:" + filePath);
			fos = new FileOutputStream(file);
			fos.write(fileInBytes);
			fos.close();
		} catch (FileNotFoundException e) {
			// Log.e(tag, "Error: " + e);
		} catch (IOException e) {
			// Log.e(tag, "Error: " + e);
		}
		// Log.i(tag, "download ready in"
		// + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
	}

	public static byte[] downloadFileFromUrl(String fileURL) {
		fileURL = CommonWS.getHttpUrl(fileURL);
		try {
			URL url = new URL(fileURL);
			// Log.i(tag, "download begining with url: " + url);

			// Open a connection to that URL.
			URLConnection ucon = url.openConnection();

			// Define InputStreams to read from the URLConnection.
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			// Read bytes to the Buffer until there is nothing more to read(-1).
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}
			return baf.toByteArray();
		} catch (MalformedURLException e) {
			// Log.e(tag, "Error: " + e);
		} catch (IOException e) {
			// Log.e(tag, "Error: " + e);
		}
		return null;
	}

	public static void saveBitmapToSDCard(Bitmap bitmapScaled, String uri) 
			throws IOException {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		bitmapScaled.compress(Bitmap.CompressFormat.PNG, 100, bytes);

		// you can create a new file name "test.jpg" in sdcard folder.
		File f = new File(uri);
		f.createNewFile();
		// write the bytes in file
		FileOutputStream fo = new FileOutputStream(f);
		fo.write(bytes.toByteArray());
	}
}